﻿using d1Common;
using d1Common.WebController;
using d1Project.Modules.Common.do4A.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace d1Project.Modules.Common.do4A.Controllers.a1
{
    [Route("do4A/a1/dept")]
    public class DeptController : Authorize1Controller
    {
        protected override DbContext dbContext
        {
            get
            {
                return this.db;
            }
        }
        private do4ADbContext db = new do4ADbContext();

        [PermissionCheck(Id = "do4A$Dept", Operation = 0)]
        public async Task<IHttpActionResult> Get()
        {
            var entities = db.Depts.AsQueryable();

            var result = await entities.OrderBy(t => t.CreateTime).Select(t => new
            {
                t.Id,
                t.Code,
                t.Name,
                t.ParentId,
                t.Path,
                t.Level
            }).ToListAsync();
            return Ok(result);
        }

        [PermissionCheck(Id = "do4A$Dept", Operation = 0)]
        public async Task<IHttpActionResult> Get(string id)
        {
            var entity = await db.Depts.Where(t => t.Id == id).Select(t => new
            {
                t.Id,
                t.Code,
                t.Name,
                t.ParentId,
                t.Path,
                t.Level
            }).FirstOrDefaultAsync();
            return Ok(entity);
        }

        [PermissionCheck(Id = "do4A$Dept", Operation = 1)]
        public async Task<IHttpActionResult> Post(DeptPostVm model)
        {
            if (!ModelState.IsValid) this.Error("请求参数不正确");
            string path = "";
            var depts = db.Depts.AsQueryable();

            var parent = await depts.Where(t => t.Id == model.ParentId).FirstOrDefaultAsync();

            var commonParent = await depts.Where(t => t.ParentId == model.ParentId).OrderByDescending(t => t.CreateTime).FirstOrDefaultAsync();
            if (commonParent != null)
            {
                path = (int.Parse(commonParent.Path) + 1).ToString().PadLeft(commonParent.Path.Length, '0');
            }
            else
            {
                path = parent.Path + "0".PadLeft(4, '0');
            }

            Dept entity = new Dept();
            entity.Id = doServices.Instance.DoCore.getGUID();
            entity.Code = model.Code;
            entity.Name = model.Name;
            entity.ParentId = model.ParentId;
            entity.Path = path;
            entity.Level = parent.Level + 1;
            entity.CreateById = this.UserId;
            entity.CreateByName = this.UserName;
            entity.CreateTime = DateTime.Now;
            entity.UpdateById = this.UserId;
            entity.UpdateByName = this.UserName;
            entity.UpdateTime = DateTime.Now;

            db.Depts.Add(entity);
            await db.SaveChangesAsync();
            return Ok();
        }

        [PermissionCheck(Id = "do4A$Dept", Operation = 2)]
        public async Task<IHttpActionResult> Put(DeptPutVm model)
        {
            if (!ModelState.IsValid) this.Error("请求参数不正确");
            var entity = await db.Depts.FindAsync(model.Id);
            entity.Code = model.Code;
            entity.Name = model.Name;
            entity.UpdateById = this.UserId;
            entity.UpdateByName = this.UserName;
            entity.UpdateTime = DateTime.Now;
            await db.SaveChangesAsync();
            return Ok();
        }

        [PermissionCheck(Id = "do4A$Dept", Operation = 4)]
        public async Task<IHttpActionResult> Delete(string id)
        {
            if (string.IsNullOrEmpty(id)) this.Error("Id不能为空");

            var depts = db.Depts.AsQueryable();

            var entity = await depts.Where(t => t.Id == id).FirstOrDefaultAsync();
            if (entity == null) this.Error("部门：" + id + "不存在");

            var entities = await depts.Where(t => t.Path.StartsWith(entity.Path)).ToListAsync();
            if (entities.Count > 0) db.Depts.RemoveRange(entities);
            await db.SaveChangesAsync();
            return Ok();
        }
    }

    public class DeptPostVm
    {
        /// <summary>
        /// 编码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 名称
        /// </summary>
        [Required]
        public string Name { get; set; }

        /// <summary>
        /// 上级ID
        /// </summary>
        [Required]
        public string ParentId { get; set; }
    }

    public class DeptPutVm
    {
        [Required]
        public string Id { get; set; }

        /// <summary>
        /// 编码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 名称
        /// </summary>
        [Required]
        public string Name { get; set; }
    }
}
